package com.kummuna.ui;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kummuna.R;
import com.kummuna.R.layout;
import com.kummuna.R.menu;
import com.kummuna.config.MainConfiguration;
import com.kummuna.util.json.JSONParser;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnLongClickListener;

public class AddWaterLeak extends Activity implements OnClickListener,
		OnLongClickListener {
	static int TAKE_PHOTO_REQUEST_CODE = 1;
	private final int SELECT_FILE = 1;
	static int TAKE_PHOTO;
	static final int MEDIA_TYPE_IMAGE = 1;
	ImageView img;
	ImageView imv;

	static Uri outputFileUriImage1;
	static Uri outputFileUriImage2;
	static Uri outputFileUriImage3;
	static Uri fileUri;

	Uri outputFileUri;
	TextView topic;
	TextView detail;
	GoogleMap map;
	LatLng latLng;
	String latitude;
	String longtitude;

	private ProgressBar progress;
	public List<NameValuePair> data;
	private JSONParser jsonParser;
	public ArrayList<HashMap<String, Uri>> result;
	MainConfiguration app = new MainConfiguration();

	private String username = MainConfiguration.username;
	private String password = MainConfiguration.password;
	private String host = MainConfiguration.host;
	public String url = MainConfiguration.addWaterLeakUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_water_leak);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			latitude = extras.getString("latitude").toString();
			longtitude = extras.getString("longtitude").toString();

			String ltlng = latitude + "," + longtitude;

			TextView latlong = (TextView) findViewById(R.id.txtlatlong);
			latlong.setText(ltlng);

			// call map
			map = ((MapFragment) getFragmentManager()
					.findFragmentById(R.id.map)).getMap();
			map.getUiSettings().setZoomControlsEnabled(false);
			map.getUiSettings().setScrollGesturesEnabled(false);

			latLng = new LatLng(Double.parseDouble(latitude),
					Double.parseDouble(longtitude));

			MarkerOptions markerOptions = new MarkerOptions();
			markerOptions.position(latLng);
			markerOptions.title(latLng.latitude + " : " + latLng.longitude);

			CameraPosition cameraPosition = new CameraPosition.Builder()
					.target(latLng).zoom(15).bearing(-30).tilt(90).build();

			// map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
			map.animateCamera(CameraUpdateFactory
					.newCameraPosition(cameraPosition));

			// Adding marker on the GoogleMap
			map.addMarker(markerOptions);
		}

		// upload picture1
		ImageView imgBtn1 = (ImageView) findViewById(R.id.imageButton1);
		imgBtn1.setOnClickListener(this);
		imgBtn1.setOnLongClickListener(this);

		// upload picture2
		ImageView imgBtn2 = (ImageView) findViewById(R.id.imageButton2);
		imgBtn2.setEnabled(false);
		imgBtn2.setOnClickListener(this);
		imgBtn2.setOnLongClickListener(this);

		// upload picture3
		ImageView imgBtn3 = (ImageView) findViewById(R.id.imageButton3);
		imgBtn3.setEnabled(false);
		imgBtn3.setOnClickListener(this);
		imgBtn3.setOnLongClickListener(this);

		// Text Topic,Detail
		topic = (TextView) findViewById(R.id.txtTopic);
		detail = (TextView) findViewById(R.id.txtDetail);

		// TopicBL data=new TopicBL();
		// data.AddTopic("1111","xxxxxx","1");

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imageButton1:
			TakePhotoOne();
			break;
		case R.id.imageButton2:
			TakePhotoTwo();
			break;
		case R.id.imageButton3:
			TakePhotoThree();
			break;
		}

	}

	public void TakePhotoOne() {
		outputFileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
		TAKE_PHOTO = 1;
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, TAKE_PHOTO_REQUEST_CODE);

	}

	public void TakePhotoTwo() {
		outputFileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
		TAKE_PHOTO = 2;
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, TAKE_PHOTO_REQUEST_CODE);
	}

	public void TakePhotoThree() {
		outputFileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
		TAKE_PHOTO = 3;
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, TAKE_PHOTO_REQUEST_CODE);

	}

	/*
	 * public void TakeGallery() {
	 * 
	 * Intent intent = new Intent( Intent.ACTION_PICK,
	 * android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	 * intent.setType("image/*"); startActivityForResult(
	 * Intent.createChooser(intent, "Select File"), SELECT_FILE);
	 * 
	 * }
	 */

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == TAKE_PHOTO_REQUEST_CODE && resultCode == RESULT_OK) {
			Toast.makeText(this, outputFileUri.toString(), Toast.LENGTH_LONG)
					.show();

			switch (TAKE_PHOTO) {
			case 1:
				outputFileUriImage1 = outputFileUri;

				imv = (ImageView) findViewById(R.id.imageButton1);
				img = (ImageView) findViewById(R.id.imageButton2);

				img.setEnabled(true);
				if (img.getDrawable() == null) {
					img.setImageResource(R.drawable.camera1);
				}
				break;
			case 2:
				outputFileUriImage2 = outputFileUri;
				imv = (ImageView) findViewById(R.id.imageButton2);
				img = (ImageView) findViewById(R.id.imageButton3);
				img.setEnabled(true);
				if (img.getDrawable() == null) {
					img.setImageResource(R.drawable.camera1);
				}
				break;
			case 3:
				outputFileUriImage3 = outputFileUri;
				imv = (ImageView) findViewById(R.id.imageButton3);
				break;
			}

			if (data != null) {
				if (data.hasExtra("data")) {
					Bitmap thumbnail = data.getParcelableExtra("data");
					imv.setImageBitmap(thumbnail);
				}
			} else {
				int width = 60;
				int height = 65;

				// Toast.makeText(getApplicationContext(),
				// String.valueOf(width),
				// 0).show();

				BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
				factoryOptions.inJustDecodeBounds = true;

				BitmapFactory.decodeFile(outputFileUri.getPath(),
						factoryOptions);

				int imageWidth = factoryOptions.outWidth;
				int imageHeight = factoryOptions.outHeight;
				int scaleFactor = Math.min(imageWidth / width, imageHeight
						/ height);
				factoryOptions.inJustDecodeBounds = false;
				factoryOptions.inSampleSize = scaleFactor;
				factoryOptions.inPurgeable = true;
				Bitmap bitmap = BitmapFactory.decodeFile(
						outputFileUri.getPath(), factoryOptions);
				imv.setImageBitmap(bitmap);

				// add image to arraylist
				/*
				 * HashMap<String,Uri> imgupload=new HashMap();
				 * imgupload.put("pic1", outputFileUriImage1);
				 * imgupload.put("pic2", outputFileUriImage2);
				 * imgupload.put("pic3", outputFileUriImage3);
				 * 
				 * result=new ArrayList<HashMap<String, Uri>>();
				 * 
				 * result.add(imgupload);
				 * 
				 * 
				 * Log.d("image : "," "+result);
				 */

			}

		} else if (resultCode == RESULT_CANCELED) {
			Toast.makeText(this, "User Cancelled : ", Toast.LENGTH_LONG).show();
		} else {
		}
	}

	private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	private static File getOutputMediaFile(int type) {
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());

		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"MyApp");

		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyApp", "failed to create directory");
				return null;
			}
		}

		// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
		// .format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			// mediaFile= new
			// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES
			// )+ "//MyApp//IMG_" + timeStamp + ".jpg");

		} else {
			return null;
		}

		return mediaFile;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.add_water_leak, menu);
		return true;
	}

	public boolean onLongClick(View v) {
		switch (v.getId()) {
		case R.id.imageButton1:
			imv = (ImageView) findViewById(R.id.imageButton1);
			break;
		case R.id.imageButton2:
			imv = (ImageView) findViewById(R.id.imageButton2);
			break;
		case R.id.imageButton3:
			imv = (ImageView) findViewById(R.id.imageButton3);
			break;
		}
		imv.setImageResource(R.drawable.camera1);
		Toast.makeText(this, "Delete Image", Toast.LENGTH_LONG).show();
		return true;
	}

	public void save(View view) throws Exception {
		// Uri image use upload on server
		/*
		 * outputFileUriImage1; outputFileUriImage2; outputFileUriImage3; topic;
		 * detail;
		 */
		Calendar cal = Calendar.getInstance();

		int millisecond = cal.get(Calendar.MILLISECOND);
		int second = cal.get(Calendar.SECOND);
		int minute = cal.get(Calendar.MINUTE);
		// 12 hour format
		int hour = cal.get(Calendar.HOUR);
		// 24 hour format
		int hourofday = cal.get(Calendar.HOUR_OF_DAY);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		int month = cal.get(Calendar.MONTH);
		int year = cal.get(Calendar.YEAR);

		String time = "  " + hourofday + "." + minute + " น.";
		String date = day + " " + (month + 1) + " " + year + time;

		new HttpUploader().execute(url);

		 Intent mapIntent = new Intent(getApplicationContext(),
		 Detectivemap.class);
		 mapIntent.putExtra("flag", "0");
		 mapIntent.putExtra("latitude", latLng.latitude + "");
		 mapIntent.putExtra("longtitude", latLng.longitude + "");
		 mapIntent.putExtra("topic", topic.getText().toString());
		 mapIntent.putExtra("detail", detail.getText().toString());
		 mapIntent.putExtra("time", date);
		 startActivity(mapIntent);
	}

	public class HttpUploader extends AsyncTask<String, Void, String> {

		URL url;
		FileInputStream fileInputStream;

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String urladddata = params[0];
//			String Topicdata = topic.getText().toString();
//			String Detaildata = detail.getText().toString();
//			String UserId = "26";
//			String Status = "0";
//			String LatPoint = latitude;
//			String LongPoint = longtitude;
			//String lineEnd = "\r\n";
			//String twoHyphens = "--";
			//String boundary = "**5870145CT**";
			
			final HttpParams httpParameters = new BasicHttpParams();
	        HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
	        HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);

			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			HttpPost httppost = new HttpPost(urladddata);
			httppost.addHeader(BasicScheme.authenticate(
					new UsernamePasswordCredentials(username, password),
					"UTF-8", false));
			Charset chars = Charset.forName("UTF-8"); 
			try {
				MultipartEntity entity = new MultipartEntity();
				
				entity.addPart("LatPoint", new StringBody(latitude, chars));
				entity.addPart("LongPoint", new StringBody(longtitude, chars));
				entity.addPart("Status", new StringBody("true"));
				entity.addPart("UserId", new StringBody("26"));
				entity.addPart("Topic", new StringBody(topic.getText().toString(), chars));
				entity.addPart("Detail", new StringBody(detail.getText().toString(), chars));
				
				 
				if(outputFileUriImage1!=null && !outputFileUriImage1.toString().equals("")){
					File file = new File(outputFileUriImage1.getPath());
					entity.addPart("fileResource1", new FileBody(file));
				}
				
				if(outputFileUriImage2!=null && !outputFileUriImage2.toString().equals("")){
					File file = new File(outputFileUriImage2.getPath());
					entity.addPart("fileResource2", new FileBody(file));
				}
				if(outputFileUriImage3!=null && !outputFileUriImage3.toString().equals("")){
					File file = new File(outputFileUriImage3.getPath());
					entity.addPart("fileResource3", new FileBody(file));
				}
				
				httppost.setEntity(entity);
				HttpResponse response = httpclient.execute(httppost);

				Log.e("test", "SC:" + response.getStatusLine().getStatusCode());

				HttpEntity resEntity = response.getEntity();

//				BufferedReader reader = new BufferedReader(
//						new InputStreamReader(
//								response.getEntity().getContent(), "UTF-8"));
//				String sResponse;
//				StringBuilder s = new StringBuilder();
//
//				while ((sResponse = reader.readLine()) != null) {
//					s = s.append(sResponse);
//				}
//				Log.e("test", "Response: " + s);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;

		}

		protected void onPostExecute() {

		}

	}

}
